package ntd.util.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.util.config.common.exception.ComException;
import ntd.util.str.enums.EnumStrTransform;

import java.util.Collection;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UtilStrTemplate {
    final static Collection<EnumStrTransform> values = EnumUtil.getEnumMap(EnumStrTransform.class).values();

    public static String replaceTemplate(String content, String params) {
        return replaceTemplate(content, JSONUtil.parseObj(params));
    }

    public static String replaceTemplate(String content, JSONObject jsonObject) {
        Pattern pattern = Pattern.compile("\\$\\{([a-z|A-Z]*)\\}");

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {
            String key = matcher.group(1);
            String replaceTemplate = matcher.group(0);
            String val = ObjectUtil.defaultIfBlank(jsonObject.getStr("__" + key), jsonObject.getStr(key));
            if (StrUtil.isBlank(val)) {
                throw new ComException("key[{}] 参数未找到", key);
            }
            content = content.replace(replaceTemplate, val);
        }

        return replaceTemplateOneFunction(content);
    }

    public static String replaceTemplateOneFunction(String content) {
        final Collection<EnumStrTransform> oneEnumStrTransforms = CollectionUtil.filter(values, enumStrTransform ->
                StrUtil.isBlank(enumStrTransform.getEndTag()));
        for (EnumStrTransform enumStrTransform : oneEnumStrTransforms) {
            String apply = enumStrTransform.getTransform().apply("");
            content = StrUtil.replace(content, enumStrTransform.getStartTag(), apply);
        }

        return replaceTemplateFunction(content);
    }

    public static String replaceTemplateFunction(String content) {
        final Collection<EnumStrTransform> enumStrTransforms = CollectionUtil.filter(values, enumStrTransform ->
                StrUtil.isNotBlank(enumStrTransform.getEndTag()));

        Function<String, String> ruleHandle = null;
        int startIndex = -1;
        int lastIndex = content.indexOf("}");
        String substring = "";
        if (lastIndex == -1) {
            return content;
        }

        for (EnumStrTransform enumStrTransform : enumStrTransforms) {
            String startTag = enumStrTransform.getStartTag();
            int i = content.substring(0, lastIndex).lastIndexOf(startTag);
            if (i > startIndex) {
                startIndex = i;
                substring = content.substring(startIndex + startTag.length(), lastIndex);
                ruleHandle = enumStrTransform.getTransform();
            }
        }

        if (startIndex == -1) {
            return content;
        }
        content = content.substring(0, startIndex) + ruleHandle.apply(substring) + content.substring(lastIndex + 1);

        return replaceTemplateFunction(content);
    }

    public static void main(String[] args) {
//        String str = "$toUpperCase{$md5{123456}}";
//        StaticLog.info(String.valueOf(str.indexOf("$md5")));
//        String s = replaceTemplateOneFunction(", $timestamp = $toUpperCase{$md5{$toHex{$timestamp}}}, $timestamp");
//        StaticLog.info(s);
        String params = "{ \"__key\": \"Gz2CehnucDBVeBh7s1pVzRVkbCKj8mlA\", \"__deviceNo\": \"AMT22030911130007\" }";
        String str = replaceTemplate("/v1/getDeviceData?deviceNo=${deviceNo}&timestamp=$timestamp&sign=$toUpperCase{$md5{$timestampdeviceNo${deviceNo}${key}}}",
                params);
        StaticLog.info("admin.yun-sense.com:80" + str);
        // admin.yun-sense.com:80/v1/getDeviceData?deviceNo=AMT22030911130007&timestamp=1648422076985&sign=92BFC4D043F124C98C0973D5E363E93B
        // admin.yun-sense.com:80/v1/getDeviceData?deviceNo=AMT21111213370013&timestamp=1647313861415&sign=2DC924F35FDF068AFDF7B158F4CB4E9C
        // admin.yun-sense.com:80/v1/getDeviceData?deviceNo=AMT21111213370013&timestamp=1647313762381&sign=B5A24AFA60DD1CA6E4E82462F18AE9C8

        StaticLog.info(HttpUtil.get("admin.yun-sense.com:80" + str));

        // E678DA003769746785603765C2955D85
        // AC90EE4875290F9D2A78B1CDDAF22FD3
        // F6FFDB673A8B085E66DC525CA8288A09
        // 07B04323CC75AEE6AF31CFDAF5C65B7E
    }
}
